package com.zrx.govern.component.easyexcel.starter.listener;

import com.zrx.govern.component.easyexcel.starter.config.ExcelConfigProperties;
import com.zrx.govern.component.easyexcel.starter.utils.JsonParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.cloud.endpoint.event.RefreshEventListener;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author zhangxiaowei
 * @desc 监听excel json配置文件刷新监听器
 */
@Slf4j
@Component
public class ExcelRefreshEventListener {

    @Autowired
    private ExcelConfigProperties excelConfigProperties;

    @Autowired
    private Environment environment;

    @EventListener(EnvironmentChangeEvent.class)
    public void listener(EnvironmentChangeEvent event) throws Exception {
        for (String key : event.getKeys()) {
            String property = environment.getProperty(key);
            log.info("refresh key: {}", key);
            log.info("refresh value: {}", property);
            try {
                JsonParseUtil.initExcelSettingJson(excelConfigProperties);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

}
